//
//  LMLocalUser.m
//  LM
//
//  Created by Kien Tran on 2/2/13.
//  Copyright (c) 2013 Kien Tran. All rights reserved.
//

#import "LMLocalUser.h"
#import "LMConstant.h"

@implementation LMLocalUser
@synthesize userName = _userName, sex = _sex, birthday = _birthday;



static LMLocalUser *_localUser;

- (id)init
{
    self = [super init];
    if (self) {
        _userName = @"";
        _sex = NO;
        _birthday = nil;
    }
    return self;
}

+ (LMLocalUser *) sharedLocalUser {
    
    if (!_localUser) {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        if ([userDefault objectForKey:kKEY_LOCAL_USER]) {
            _localUser = [[LMLocalUser alloc] initWithDictionary:[userDefault objectForKey:kKEY_LOCAL_USER]];
        }
        
        
        if (!_localUser) {
            _localUser = [[LMLocalUser alloc] init];
            _localUser.userName = @"No name";
            _localUser.birthday = [NSDate date];
        }
    }
    
    return _localUser;
}

+ (void) setSharedLocalUser:(LMLocalUser *)localUser {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:[localUser dictionary] forKey:kKEY_LOCAL_USER];
    
    _localUser = [localUser copy];
}

- (id) copy {
    LMLocalUser *copyingLocalUser = [[LMLocalUser alloc] init];
    
    [copyingLocalUser setUserName:self.userName];
    [copyingLocalUser setSex:self.sex];
    [copyingLocalUser setBirthday:self.birthday];
    
    return copyingLocalUser;
}

- (void)copy:(LMLocalUser *)sender {
    [self setUserName:sender.userName];
    [self setSex:sender.sex];
    [self setBirthday:sender.birthday];
}

- (NSDictionary *)dictionary {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    if (self.userName) {
        [dic setObject:self.userName forKey:@"user_name"];
    }

    [dic setObject:[NSString stringWithFormat:@"%d",self.sex] forKey:@"sex"];
    
    if (self.birthday) {
        [dic setObject:self.birthday forKey:@"birthday"];
    }
    
    return dic;
}

- (id)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
        _userName = [dictionary objectForKey:@"user_name"];
        _sex = [[dictionary objectForKey:@"sex"] boolValue];
        _birthday = [dictionary objectForKey:@"birthday"];
    }
    return self;
}

- (id)initWithName:(NSString *)name sex:(BOOL)isMale andBirthday:(NSDate *)birthday {
    self = [super init];
    
    if (self) {
        _userName = [name copy];
        _sex = isMale;
        _birthday = [birthday copy];
    }
    
    return self;
}

- (NSString *) getBirthdayString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    dateFormatter.dateFormat = kDATE_FORMAT;
    
    if (self.birthday) {
        return [dateFormatter stringFromDate:self.birthday];
    }
    
    return nil;
}
@end
